<?php

use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;


class UserController extends CloudControllerBase
{

    /******************************    用户管理    ***********************************************************/


    public function addUserAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        switch ($this->getRequestAction()) {
            case  $this::REQUEST_ACTION_ADD: {

                $this->checkRequestParams(array(
                    array(
                        "key" => "password",
                        "type" => "length",
                        "min" => 6,
                        "max" => 32,
                        "message" => "密码长度在6-32字符之间"),
                    array(
                        "key" => "phone",
                        "type" => "phone",
                        "message" => "手机号格式不正确"),
                ));
                $password = $this->getPost("password");
                $phone = $this->getPost("phone");
                //检验用户是否存在
                $total = $this->fetchColumn("select count(*) as total from user where phone='$phone'");
                if ($total > 0) {
                    $this->returnError("该手机号已经被注册");
                }
                $nickname = substr($phone, 7);
                $token = $this->guid();
                // 插入新用户
                $salted = $password . '{' . $token . '}';
                $password_salt = bin2hex(hash('sha512', $salted, true));
                $user_id = $this->insert("user", array(
                    "phone" => $phone,
                    "password" => $password_salt,
                    "nickname" => $nickname,
                    "sex" => null,
                    "token" => $token,
                    "ios_token" => $token,
                    "cloud_token" => $token,
                    "salt" => $token,
                    "password_salt" => $password_salt));
                if ($user_id > 0) {
                    $this->saveOperationLog("添加用户", "添加用户,user id=" . $user_id . ",手机号:" . $phone);
                    $this->returnSuccess("添加成功");
                } else {
                    $this->returnError("添加失败");
                }
            };
                break;
        }
    }


    public function listAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $tableName = "(SELECT user.*,temp.system_name from user left join 
(SELECT u.user_id,s.system_name from bind_user_system as u LEFT JOIN subsystem_info as s on s.id=u.system_id ) temp on temp.user_id=user.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "nickname" => "昵称",
                    "phone" => "登录手机",
                    "system_name" => "所属系统",
                    "permission_local_gps" => "本地GPS权限",
                    "permission_p40" => "P40相机权限",
                    "video_route" => "视频航线权限",
                    "sex" => "性别",
                    "online" => "状态",
                    "company" => "公司",
                    "city" => "城市",
                    "created_at" => "创建时间"
                ), $tableName, array(
                    ["nickname", "like", "%", "%"],
                    ["phone", "like", "%", "%"],
                    ["company", "like", "%", "%"],
                    ["city", "like", "%", "%"]
                ), "created_at desc", "id");
            };
                break;
        }
    }


    public function detailAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        switch ($this->getRequestAction()) {

            case  $this::REQUEST_ACTION_UPDATE: {
                $validation = new Phalcon\Validation();
                $validation->add('id', new PresenceOf(array('message' => 'id为空')));
                $this->checkRequest($validation, $this->request->getPost());
                $systemId = $this->getPost("id");
                $this->generateUpdateData(array(
                    "table" => "user",
                    "fieldList" => array("nickname", "permission_local_gps", "permission_p40", "video_route",
                        "sex", "online", "city", "company", "email"),
                    "where" => " id=$systemId"
                ));
            };
                break;
            default: {
                $id = intval($this->getQuery("id"));
                $tableName = "user";
                $this->generateDetailData(array(
                    "table" => $tableName,
                    "column" => array(
                        ["phone", "登录手机号", "disabled"],
                        ["email", "邮箱", ""],
                        ["nickname", "昵称", ""],
                        ["permission_local_gps", "本地GPS权限", "", true, "", "select", array("未知" => -1, "不可用" => 0, "可用" => 1)],
                        ["permission_p40", "P40相机权限", "", true, "", "select", array("未知" => -1, "不可用" => 0, "可用" => 1)],
                        ["video_route", "视频航线权限", "", true, "", "select", array("未知" => -1, "不可用" => 0, "可用" => 1)],
                        ["sex", "性别", "", true, "", "select", array("未知" => -1, "男" => 0, "女" => 1)],
                        ["online", "状态", "", true, "", "select", array("未知" => -1, "不可用" => 0, "可用" => 1)],
                        ["company", "公司", ""],
                        ["city", "城市", ""],
                        ["created_at", "创建时间", "disabled"],
                        ["id", "", "", false],
                    ),
                    "title" => "ID",
                    "titleKey" => "id",
                    "keyName" => "id",
                    "where" => " id=$id",
                ));
            };
        }


    }
    
    public function aopaAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $action = $this->getRequestAction();
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "aopa ".json_encode($action)."\r\n", FILE_APPEND);
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
            break;
            case  $this::REQUEST_ACTION_LIST: {

                //$strWhereData = json_decode($this->getPost("filter_list"), true);

                $table = "(SELECT * from user where aopa=1)";
                $this->postQueryByPage(array(
                        
                        "nickname" => "用户昵称",
                        "phone" => "手机号",
                        "created_at" => "创建时间",
                        "online" => "是否可用",
                        "aopa" => "aopa权限",
                        
                ), $table, array(

                ), "id asc", "id");
            };
            break;
        }
    }
    
    public function addAopaAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        if (is_uploaded_file ( $_FILES ['aopa'] ['tmp_name'] )) {
            $allowedExts = array (
                    "txt"
            );
            $extension = end ( explode ( ".", $_FILES ["aopa"] ["name"] ) );
            if ($extension == "txt") {
                $content = file_get_contents($_FILES ['aopa'] ['tmp_name']);
                $users = explode("\r\n", $content);
                $data =  array('success'=>array(),'error'=>array());
                foreach ($users as $user){
                    $sql = "select id from user where phone = '" . trim($user) . "'";
                    $id = $this->fetchColumn($sql);
                    if($id){
                        $this->update("user", array('aopa'=>true), 'id='.$id);
                        $data['success'][] = $user;
                    }else if(!empty($user)){
                        $data['error'][] = $user;
                    }
                }
            }else{
                $this->returnError('类型错误');
            }
        }
        $this->returnJson($data);
    }
    
    public function deleteAopaAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        if (is_uploaded_file ( $_FILES ['aopa'] ['tmp_name'] )) {
            $allowedExts = array (
                    "txt"
            );
            $extension = end ( explode ( ".", $_FILES ["aopa"] ["name"] ) );
            if ($extension == "txt") {
                $content = file_get_contents($_FILES ['aopa'] ['tmp_name']);
                $users = explode("\r\n", $content);
                $data =  array('success'=>array(),'error'=>array());
                foreach ($users as $user){
                    $sql = "select id from user where phone = '" . trim($user) . "'";
                    $id = $this->fetchColumn($sql);
                    if($id){
                        $this->update("user", array('aopa'=>false), 'id='.$id);
                        $data['success'][] = $user;
                    }else if(!empty($user)){
                        $data['error'][] = $user;
                    }
                }
            }else{
                $this->returnError('类型错误');
            }
        }
        $this->returnJson($data);
    }

    public function listLoginRecordAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT l.*,u.phone from login_record as l LEFT JOIN user as u on u.id=l.user_id)";
                $this->postQueryByPage(array(

                    "login_type" => "登录类型",
                    "created_at" => "登录时间",
                    "user_id" => "用户ID",
                    "phone" => "登录手机",
                    "ip" => "登录IP",
                    "device_id" => "设备ID",
                    "user_agent" => "客户端",

                ), $table, array(
                    ["id", "=", "", ""],
                    ["login_type", "=", "", ""],
                    ["phone", "like", "%", "%"],
                    ["user_agent", "like", "%", "%"],
                    ["device_id", "like", "%", "%"],
                    ['created_at_start', '>=', '', '', "created_at"],
                    ['created_at_end', '<=', '', '', "created_at"]
                ), "created_at desc", "id");
            };
                break;
        }
    }

    public function addAction()
    {

    }

    public function addMonitorAction()
    {

    }

    public function addUserStatusAction()
    {

    }


    public function indexAction()
    {

    }

    public function registerAction()
    {

    }

    /******************************    用户公开接口    ***********************************************************/

    // 新用户注册
    public function registerDoAction()
    {

        // 数据有效性验证
        $validation = new Phalcon\Validation();
        $validation->add('phone', new RegexValidator(array('pattern' => '/^[0-9]{11}$/', 'message' => '电话号码格式不正确')));
        $validation->add('phone', new PresenceOf(array('message' => '手机号不能为空')));
        $validation->add('validate', new Between(array('minimum' => 1000, 'maximum' => 9999, 'message' => '验证码格式不正确')));
        $validation->add('password', new StringLength(array('max' => 32, 'min' => 6, 'messageMaximum' => '密码为6到32位字符', 'messageMinimum' => '密码为6到32位字符')));
        $this->checkRequest($validation, $this->request->getPost());

        $expire = $this->redisExpire['user'];

        // 获得数据
        $phone = $this->getPost("phone");
        $validate = $this->getPost("validate");
        $password = $this->getPost("password");
        $repeatPassword = $this->getPost("repeat_password");

        if ($password != $repeatPassword) {
            $this->returnError("两次输入的密码不相同。");
        }

        // 检测用户是否存在
        $sql = "SELECT * FROM user where phone = '$phone'";
        $record = $this->fetchOne($sql);
        if ($record > 0) {
            $this->returnError('此用户已存在！');
        }

        // 监测验证码是否正确
        if ($validate != $this->redis->get("validate-$phone")) {
            $this->returnError("验证码不正确。");
        }

        $nickname = substr($phone, 7);

        $token = $this->guid();
        // 插入新用户
        $salted = $password . '{' . $token . '}';
        $password_salt = bin2hex(hash('sha512', $salted, true));

        $user_id = $this->insert("user", array(
            "phone" => $phone,
            "password" => $password_salt,
            "nickname" => $nickname,
            "sex" => null,
            "token" => $token,
            "ios_token" => $token,
            "cloud_token" => $token,
            "salt" => $token,
            "password_salt" => $password_salt));

//         $sql = "SELECT * FROM user where id = $user_id";
//         $applyUser = $this->fetchOne($sql);

        $this->session->set('token', $token);

    }

    // 用户登录
    public function loginAction()
    {
        // 数据有效性验证
    }

    /**
     * 用户登录,并且存储session相关登录信息
     */
    public function doLoginAction()
    {

        // 数据有效性验证
        $this->checkRequestParams(array(
                array(
                    "key" => "phone",
                    "type" => "presence&phone",
                    "message" => "请输入正确电话号码"),
                array(
                    "key" => "password",
                    "type" => "length",
                    'max' => 32,
                    'min' => 6,
                    'message' => '密码为6到32位字符',
                ),
            )
        );
        // 获得数据
        $phone = $this->getPost('phone');
        $password = $this->getPost('password');
        $deviceId = $this->getPost('device_id');
        $jPushToken = $this->getPost('jpush_token');
        $expire = $this->redisExpire['user'];

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "login phone:$phone, password:$password, deviceId:$deviceId, jPushToken:$jPushToken\r\n", FILE_APPEND);

        $sql = "select * from user where phone = '$phone'";
        //请不要缓存用户信息!
        $record = $this->fetchOne($sql);
        if (empty($record)) {
            $this->returnError("该手机号没有注册过。");
        }

        if ($record["online"] == 0) {
            $this->returnError("您的账户被锁定了。");
        }

        if ($record['password_salt'] != bin2hex(hash('sha512', $password . '{' . $record['salt'] . '}', true))) {
            $this->returnError("密码错误，请检查键盘大小写是否有输入错误。");
        }
        //查找所属的
        $userId = $record["id"];
        $sqlBindSystem =
            "SELECT * from bind_user_system WHERE user_id=$userId";
        $bindInfo = $this->fetchOne($sqlBindSystem);
        $userRoleId=intval($bindInfo["user_role_id"]);
        $isSystemAdmin = $userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN ? true : false;
        $roleInfoData = $this->getRoleInfo();
        $userRoleName=$roleInfoData[$userRoleId];
        if (empty($bindInfo)) {
            if (!$isSystemAdmin) {
                $this->returnError("您当前没有所属系统,请联系管理员。");
            }
        }
        //密码验证成功
        $myuser = new MonitorLoginUser();
        $myuser->userId = intval($userId);
        $myuser->name = empty($record["nickname"]) ? "CLOUD" : $record["nickname"];
        $myuser->phone = $record["phone"];
        $myuser->subsystemId = intval($bindInfo["system_id"]);
        $myuser->roleName = $userRoleName ? $userRoleName : "未知";
        $myuser->userRoleId = $userRoleId;
        $myuser->isSystemAdmin = $isSystemAdmin;
        $myuser->email = $record["email"];
        $myuser->userAuthMenu = $record["user_auth_menu"];
        $myuser->iconUrl=$record["icon_url"];
        $token = $this->guid();
        $myuser->token = $token;

        $ip = $_SERVER["REMOTE_ADDR"];
        if (isset($_SERVER["HTTP_USER_AGENT"])) {
            $userAgent = addslashes($_SERVER["HTTP_USER_AGENT"]);
        } else {
            $userAgent = "";
        }
        //更新用户loginToken
        $sql = "update user set cloud_token = '$token', last_active_at = now(),jpush_token='$jPushToken' where id = $userId";
        $this->execute($sql);
        //更新用户的
        $sql = "insert into login_record(user_id, ip, device_id, user_agent,login_type) values($userId, '$ip', '$deviceId', '$userAgent',1)";
        $this->execute($sql);

        $this->redis->setex($token, $expire, $userId);
        $this->session->set($this::SESSION_LOGIN_USER, $myuser);
        $this->session->set($this::SESSION_DOWNLOAD_CENTER, true);//固件下载中心session

        $sql = "select * from user where id = {$record["id"]}";
        $record = $this->fetchOne($sql);
        $value = json_encode($record, true);
        $this->redis->setex("sql:$sql", $expire, $value);
        $sql = "select * from user where phone = '$phone'";
        $this->redis->setex("sql:$sql", $expire, $value);
        $sql = "select * from user where cloud_token = '{$token}'";
        $this->redis->setex("sql:$sql", $expire, $value);

        $this->returnSuccess("");

    }

    //替换登录界面logo
    public function changeIcoAction()
    {
        $phone = $this->getPost("phone");
        $sql = "SELECT
                    i.system_logo_url,i.system_title
                FROM
                    subsystem_info AS i
                WHERE
                    i.id = (
                        SELECT
                            MAX(s.system_id)
                        FROM
                            bind_user_system AS s
                        WHERE
                            s.user_id = (
                                SELECT
                                    `user`.id
                                FROM
                                    `user`
                                WHERE
                                    `user`.phone = $phone
                            )
                    )";
        $data = $this->fetchOne($sql);
        $this->returnJson($data);
    }


    // 用户退出
    public function doLogoutAction()
    {
        $user = $this->getMonitorLoginUser();
        $token = $user->token;

        $this->session->destroy();
//         $this->cookies->delete('organization');
        $expire = $this->redisExpire['user'];

        $this->redis->delete($token);
        $sql = "select * from user where cloud_token = '{$token}'";
        $record = $this->fetchOne($sql, $expire);
        $this->redis->delete("sql:$sql");
        $sql = "select * from user where phone = '{$record["phone"]}'";
        $this->redis->delete("sql:$sql");
        $sql = "select * from user where id = {$record["id"]}";
        $this->redis->delete("sql:$sql");

        $this->returnSuccess('退出成功');
    }

    
    public function receiveQcloudReturnAction()
    {
        file_put_contents("./Qcloud_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie get:".json_encode($_GET)."\r\n", FILE_APPEND);
        file_put_contents("./Qcloud_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie post:".json_encode($_POST)."\r\n", FILE_APPEND);
        file_put_contents("./Qcloud_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie HTTP_RAW_POST_DATA:".json_encode($GLOBALS['HTTP_RAW_POST_DATA'])."\r\n", FILE_APPEND);
        file_put_contents("./Qcloud_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie request:".json_encode($_REQUEST)."\r\n", FILE_APPEND);
        
//         $data = '{"time":1514454499,"nationcode":"86","mobile":"13810812238","text":"Tjfj","sign":"\u98DE\u9A6C\u673A\u5668\u4EBA"}';
//         $data = '{"time":1514519466,"nationcode":"86","mobile":"13810812238","text":"Tytj","sign":"\u98DE\u9A6C\u673A\u5668\u4EBA"}';
        $result = json_decode($GLOBALS['HTTP_RAW_POST_DATA'], true);
//         $result = json_decode($data, true);
        
        if ($this->redis->exists("validate-{$result['time']}-{$result['mobile']}")) {
            header("Content-Type:application/json; charset=UTF-8");
            $response = json_encode(array('result' => 0, 'errmsg' => "OK"));
            header("content-length:" . strlen($response));
            echo $response;
            exit();
        } else {
            $expire = 1200;
            $sendExpire = $this->redisExpire ['sms'];
            $sql = "select * from (select * from send_sms where phone='{$result['mobile']}' and type<>0 and status=0 and created_at>date_add(now(), INTERVAL -" . ($sendExpire/60) . " MINUTE) order by created_at desc) as a group by user_id,phone,type,foreign_id ORDER BY created_at desc";
            $sendSms = $this->fetchAll($sql);
            
            if (!empty($sendSms)) {
                
                foreach ($sendSms as $sms) {
                    if ($sms['type'] == '1') {
                        $sql = "select id,nickname from user where phone = '{$result['mobile']}'";
                        $user = $this->fetchOne($sql);
                        
                        $this->insert("receive_sms", array(
                                "user_id" => $user['id'],
                                "phone" => $result['mobile'],
                                "content" => $result['text'],
                                "created_at" => date('Y-m-d H:i:s',$result['time'])));
                        
                        if ($this->redis->exists("system-add-{$result['mobile']}")) {
                            $sql = "select u.id,u.system_id,s.system_name from system_add_user as u,subsystem_info as s where u.system_id=s.id and u.id = {$sms['foreign_id']} and status<>2 order by id desc";
                            $system = $this->fetchOne($sql);
                            
                            if ($system) {
                                if (strtolower(trim($result['text'])) == 'tytj') {
                                    $sql = "SELECT s.system_name FROM bind_user_system as b, subsystem_info as s where b.system_id=s.id and b.user_id = {$user['id']}";
                                    $bind = $this->fetchOne($sql);
                                    
                                    if ($bind) {
                                        $text = "因您已绑定过" . $bind['system_name'] . "添加失败";
                                        $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                        if ($smsResult['code'] != '0') {
                                            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                        }
                                    } else {
                                        $this->update("system_add_user", array(
                                                "receive_at" => date('Y-m-d H:i:s'),
                                                "status" => 2), "id = " . $system['id']);
                                        
                                        $this->insert("bind_user_system", array(
                                                "user_id" => $user['id'],
                                                "system_id" => $system['system_id'],
                                                "user_role_id" => 3,
                                                "real_name" => $user['nickname'],
                                                "created_at" => date('Y-m-d H:i:s')));
                                        
                                        $text = "用户已添加成功";
                                        $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                        if ($smsResult['code'] != '0') {
                                            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                        }
                                    }
                                    
                                } else {
                                    $this->update("system_add_user", array(
                                            "receive_at" => date('Y-m-d H:i:s'),
                                            "status" => 3), "id = " . $system['id']);
                                    
                                    $text = "因回复错误添加失败";
                                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                    if ($smsResult['code'] != '0') {
                                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                    }
                                }
                            } else {
                                $text = "用户已添加成功";
                                $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                if ($smsResult['code'] != '0') {
                                    file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                }
                            }
                        }
                        
                        $this->update("send_sms", array("status" => 2), "id = " . $sms['id']);
                        break;
                    } else if ($sms['type'] == '2') {
                        $this->insert("receive_sms", array(
                                "user_id" => $sms['user_id'],
                                "phone" => $result['mobile'],
                                "content" => $result['text'],
                                "created_at" => date('Y-m-d H:i:s',$result['time'])));
                        
                        if ($this->redis->exists("bind-plane-{$result['mobile']}")) {
                            $sql = "select u.id,u.system_id,u.plane_id,s.system_name from system_add_plane as u,subsystem_info as s where u.system_id=s.id and u.id = {$sms['foreign_id']} and status<>2 order by id desc";
                            $system = $this->fetchOne($sql);
                            
                            if ($system) {
                                if (strtolower(trim($result['text'])) == 'tjfj') {
                                    $sql = "SELECT s.system_name FROM bind_plane_system as b, subsystem_info as s where b.system_id=s.id and b.plane_id = {$system['plane_id']}";
                                    $bind = $this->fetchOne($sql);
                                    
                                    if ($bind) {
                                        $text = "因飞机已绑定过" . $bind['system_name'] . "添加失败";
                                        $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                        if ($smsResult['code'] != '0') {
                                            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                        }
                                    } else {
                                        $sql_count = "SELECT count(id) as id FROM bind_plane_system where system_id = {$system['system_id']}";
                                        $planeCount = $this->fetchColumn($sql_count);
                                        $sql_limit = "SELECT plane_limit,system_name from subsystem_info WHERE id=" . $system['system_id'];
                                        $planeLimit = $this->fetchOne($sql_limit);
                                        
                                        if ($planeCount < $planeLimit['plane_limit']) {
                                            $this->update("system_add_plane", array(
                                                    "receive_at" => date('Y-m-d H:i:s'),
                                                    "status" => 2), "id = " . $system['id']);
                                            
                                            $this->insert("bind_plane_system", array(
                                                    "user_id" => $sms['user_id'],
                                                    "system_id" => $system['system_id'],
                                                    "plane_id" => $system['plane_id'],
                                                    "created_at" => date('Y-m-d H:i:s')));

                                            $text = "飞机已添加成功";
                                            $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                            if ($smsResult['code'] != '0') {
                                                file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                            }
                                        }else{
                                            $text = "飞机添加失败，{$planeLimit['system_name']}系统中已有{$planeLimit['plane_limit']}架飞机";
                                            $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                            if ($smsResult['code'] != '0') {
                                                file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                            }
                                        }
                                    }
                                    
                                } else {
                                    $this->update("system_add_plane", array(
                                            "receive_at" => date('Y-m-d H:i:s'),
                                            "status" => 3), "id = " . $system['id']);
                                    
                                    $text = "因回复错误添加失败";
                                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                    if ($smsResult['code'] != '0') {
                                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                    }
                                }
                            } else {
                                $text = "飞机已添加成功";
                                $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                if ($smsResult['code'] != '0') {
                                    file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                }
                            }
                        }
                        $this->update("send_sms", array("status" => 2), "id = " . $sms['id']);
                        break;
                    }
                }
            } else {
                $sql_his = "select * from (select * from send_sms where phone='{$result['mobile']}' and type<>0 and created_at>date_add(now(), INTERVAL -" . ($sendExpire/60) . " MINUTE) order by created_at desc) as a group by user_id,phone,type,foreign_id ORDER BY created_at desc";
                $sendSmsHis = $this->fetchAll($sql_his);
                if($sendSmsHis){
                    $text = "短信已经回复过，如需添加请联系管理员重新发送请求";
                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                    if ($smsResult['code'] != '0') {
                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                    }
                }else{
                    $text = "因回复超时添加失败";
                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                    if ($smsResult['code'] != '0') {
                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "Qcloud return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                    }
                }
            }
            
            $this->redis->setex("validate-{$result['time']}-{$result['mobile']}", $expire, $result['text']);
            
            header("Content-Type:application/json; charset=UTF-8");
            $response = json_encode(array('result' => 0, 'errmsg' => "OK"));
            header("content-length:" . strlen($response));
            echo $response;
            file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()) . ':' . __METHOD__ . ':' . "recevie SUCCESS\r\n", FILE_APPEND);
            exit();
        }
        
//         $appid = '1400058333';
//         $appkey = 'cf3e7c976b6f93a3befd4ca0ef661bf2';
        
//         try {
//             $puller = new Qcloud\Sms\SmsStatusPuller($appid, $appkey);
            
//             // 拉取短信回执
//             $callbackResult = $puller->pullCallback(10);
//             $callbackRsp = json_decode($callbackResult);
//             echo $callbackResult;
            
//             // 拉取回复
//             $replyResult = $puller->pullReply(10);
//             $replyRsp = json_decode($replyResult);
//             echo $replyResult;
//         } catch (\Exception $e) {
//             echo var_dump($e);
//         }
        
//         header("Content-Type:application/json; charset=UTF-8");
//         $response = json_encode(array('result' => 0, 'errmsg' => "OK"));
//         header("content-length:" . strlen($response));
//         echo $response;
//         exit();
    }
    
    // 短信接收
    public function receiveSmsReturnAction()
    {
//         $user = $this->getLoginUser();
//         $data = '{\"id\":\"2a70c6bb4f2845da816ea1bfe5732747\",\"mobile\":\"15205201314\",\"reply_time\":\"2014-03-17 22:55:21\",\"text\":\"\u6536\u5230\u4e86\uff0c\u8c22\u8c22\uff01\",\"extend\":\"01\",\"base_extend\":\"8888\",\"_sign\":\"393d079e0a00912335adfe46f4a2e10f\"}';
        $data = $this->getPost('sms_reply');
//         $data = '%7B%22id%22%3A%2232a9630e6b0d49acbf67d5dde0fd3eff%22%2C%22mobile%22%3A%2213810812238%22%2C%22text%22%3A%22%E6%94%B6%E5%88%B0%E4%BA%86%EF%BC%8C8%2F3%22%2C%22reply_time%22%3A%222017-08-03+17%3A35%3A53%22%2C%22extend%22%3A%22%22%2C%22base_extend%22%3A%22514707%22%2C%22_sign%22%3A%22d02653fba99317588d0682135c579426%22%7D';
        $data = urldecode($data);


//         file_put_contents("./log_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie get:".json_encode($_GET)."\r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "recevie post:$data\r\n", FILE_APPEND);
//         file_put_contents("./log_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie request:".json_encode($_REQUEST)."\r\n", FILE_APPEND);
//         $data = str_replace("\\\"","\"",$data);
        $result = json_decode($data, true);
        if ($this->redis->exists("validate-{$result['id']}")) {
            echo 'SUCCESS';
        } else {
            $sign = $result['_sign'];
            unset($result['_sign']);
            ksort($result);
            $str = implode(',', $result);
            $expire = 1200;
            $sendExpire = $this->redisExpire ['sms'];
            if ($sign == md5($str . ',' . $this->yunpian['apikey'])) {

                $sql = "select * from (select * from send_sms where phone='{$result['mobile']}' and type<>0 and status=0 and created_at>date_add(now(), INTERVAL -" . ($sendExpire/60) . " MINUTE) order by created_at desc) as a group by user_id,phone,type,foreign_id ORDER BY created_at desc";
                $sendSms = $this->fetchAll($sql);

                if (!empty($sendSms)) {

                    foreach ($sendSms as $sms) {
                        if ($sms['type'] == '1') {
                            $sql = "select id,nickname from user where phone = '{$result['mobile']}'";
                            $user = $this->fetchOne($sql);

                            $this->insert("receive_sms", array(
                                "user_id" => $user['id'],
                                "sms_id" => $result['id'],
                                "phone" => $result['mobile'],
                                "content" => $result['text'],
                                "created_at" => $result['reply_time'],
                                "extend" => $result['extend'],
                                "base_extend" => $result['base_extend']));

                            if ($this->redis->exists("system-add-{$result['mobile']}")) {
                                $sql = "select u.id,u.system_id,s.system_name from system_add_user as u,subsystem_info as s where u.system_id=s.id and u.id = {$sms['foreign_id']} and status<>2 order by id desc";
                                $system = $this->fetchOne($sql);

                                if ($system) {
                                    if (strtolower(trim($result['text'])) == 'tytj') {
//                                     if (trim($result['text']) == $this->redis->get("system-add-{$result['mobile']}")) {

                                        $sql = "SELECT s.system_name FROM bind_user_system as b, subsystem_info as s where b.system_id=s.id and b.user_id = {$user['id']}";
                                        $bind = $this->fetchOne($sql);

                                        if ($bind) {
//                                             $this->update("bind_user_system", array(
//                                                 "system_id" => $system['system_id'],
//                                                 "user_role_id" => 3,
//                                                 "real_name" => $result['nickname'],
//                                                 "created_at" => date('Y-m-d H:i:s')),
//                                                 'id=' . $bind['id']);

//                                             $text="【飞马机器人】您已绑定过".$bind['system_name']."系统,不能添加";
                                            $text = "【飞马机器人】因您已绑定过" . $bind['system_name'] . "添加失败回T退订";
                                            $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                            $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                            if ($smsResult['code'] != '0') {
                                                file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                                 $this->returnError("发送失败");
                                            }
                                        } else {
                                            $this->update("system_add_user", array(
                                                "receive_at" => date('Y-m-d H:i:s'),
                                                "status" => 2), "id = " . $system['id']);

                                            $this->insert("bind_user_system", array(
                                                "user_id" => $user['id'],
                                                "system_id" => $system['system_id'],
                                                "user_role_id" => 3,
                                                "real_name" => $user['nickname'],
                                                "created_at" => date('Y-m-d H:i:s')));

                                            $text = "【飞马机器人】用户已添加成功回T退订";
                                            $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                            $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                            if ($smsResult['code'] != '0') {
                                                file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                                //                                             $this->returnError("发送失败");
                                            }
                                        }

                                    } else {
                                        $this->update("system_add_user", array(
                                            "receive_at" => date('Y-m-d H:i:s'),
                                            "status" => 3), "id = " . $system['id']);

                                        $text = "【飞马机器人】因回复错误添加失败回T退订";
                                        $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                        $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                        if ($smsResult['code'] != '0') {
                                            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                             $this->returnError("发送失败");
                                        }
                                    }
                                } else {
                                    $text = "【飞马机器人】用户已添加成功回T退订";
                                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                    $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                    if ($smsResult['code'] != '0') {
                                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
                                        //                                             $this->returnError("发送失败");
                                    }
                                }
                            }
                            
                            $this->update("send_sms", array("status" => 2), "id = " . $sms['id']);
                            break;
                        } else if ($sms['type'] == '2') {
                            $this->insert("receive_sms", array(
                                "user_id" => $sms['user_id'],
                                "sms_id" => $result['id'],
                                "phone" => $result['mobile'],
                                "content" => $result['text'],
                                "created_at" => $result['reply_time'],
                                "extend" => $result['extend'],
                                "base_extend" => $result['base_extend']));

                            if ($this->redis->exists("bind-plane-{$result['mobile']}")) {
                                $sql = "select u.id,u.system_id,u.plane_id,s.system_name from system_add_plane as u,subsystem_info as s where u.system_id=s.id and u.id = {$sms['foreign_id']} and status<>2 order by id desc";
                                $system = $this->fetchOne($sql);

                                if ($system) {
                                    if (strtolower(trim($result['text'])) == 'tjfj') {
//                                     if(trim($result['text'])==$this->redis->get("bind-plane-{$result['mobile']}")){

                                        $sql = "SELECT s.system_name FROM bind_plane_system as b, subsystem_info as s where b.system_id=s.id and b.plane_id = {$system['plane_id']}";
                                        $bind = $this->fetchOne($sql);

                                        if ($bind) {
//                                             $this->update("bind_plane_system", array(
//                                                     "system_id" => $system['system_id'],
//                                                     "user_id" => $sms['user_id'],
//                                                     "created_at" => date('Y-m-d H:i:s')),
//                                                     'id='.$bind['id']);

//                                             $text="【飞马机器人】您的飞机已绑定过".$bind['system_name']."系统,不能添加";
                                            $text = "【飞马机器人】因飞机已绑定过" . $bind['system_name'] . "添加失败回T退订";
                                            $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                            $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                            if ($smsResult['code'] != '0') {
                                                file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                                 $this->returnError("发送失败");
                                            }
                                        } else {
                                            $sql_count = "SELECT count(id) as id FROM bind_plane_system where system_id = {$system['system_id']}";
                                            $planeCount = $this->fetchColumn($sql_count);
                                            $sql_limit = "SELECT plane_limit,system_name from subsystem_info WHERE id=" . $system['system_id'];
                                            $planeLimit = $this->fetchOne($sql_limit);
                                            
                                            if ($planeCount < $planeLimit['plane_limit']) {
                                                $this->update("system_add_plane", array(
                                                    "receive_at" => date('Y-m-d H:i:s'),
                                                    "status" => 2), "id = " . $system['id']);
    
                                                $this->insert("bind_plane_system", array(
                                                    "user_id" => $sms['user_id'],
                                                    "system_id" => $system['system_id'],
                                                    "plane_id" => $system['plane_id'],
                                                    "created_at" => date('Y-m-d H:i:s')));
    
    //                                         $text="【飞马机器人】您的飞机已添加到".$system['system_name']."系统";
                                                $text = "【飞马机器人】飞机已添加成功回T退订";
                                                $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                                $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                                if ($smsResult['code'] != '0') {
                                                    file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
    //                                             $this->returnError("发送失败");
                                                }
                                            }else{
                                                $text = "【飞马机器人】飞机添加失败，{$planeLimit['system_name']}系统中已有{$planeLimit['plane_limit']}架飞机，回T退订";
                                                $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                                $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                                if ($smsResult['code'] != '0') {
                                                    file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                             $this->returnError("发送失败");
                                                }
                                            }
                                        }

                                    } else {
                                        $this->update("system_add_plane", array(
                                            "receive_at" => date('Y-m-d H:i:s'),
                                            "status" => 3), "id = " . $system['id']);

                                        $text = "【飞马机器人】因回复错误添加失败回T退订";
                                        $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                        $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                        if ($smsResult['code'] != '0') {
                                            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                             $this->returnError("发送失败");
                                        }
                                    }
                                } else {
                                    $text = "【飞马机器人】飞机已添加成功回T退订";
                                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                                    $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                                    if ($smsResult['code'] != '0') {
                                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                                 $this->returnError("发送失败");
                                    }
                                }
                            }
                            $this->update("send_sms", array("status" => 2), "id = " . $sms['id']);
                            break;
                        }
                    }
                } else {
                    $text = "【飞马机器人】因回复超时添加失败回T退订";
                    $smsResult = $this->sendSmsContent($result['mobile'], $text);
                    $smsResult = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
                    if ($smsResult['code'] != '0') {
                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($smsResult) . " \r\n", FILE_APPEND);
//                                             $this->returnError("发送失败");
                    }
                }

                $this->redis->setex("validate-{$result['id']}", $expire, $result['text']);
                echo 'SUCCESS';
                file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()) . ':' . __METHOD__ . ':' . "recevie SUCCESS\r\n", FILE_APPEND);
            } else {
                echo "FALSE";
                file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()) . ':' . __METHOD__ . ':' . "recevie FALSE\r\n", FILE_APPEND);
            }
        }
    }

    // 查看当前用户个人信息
    public function profileAction()
    {
        $this->returnJson($this->getMonitorLoginUser());
    }

    public function editAction()
    {

    }

    public function editMyProfileAction()
    {

    }

    //获取当前个人用户信息
    public function myProfileAction()
    {
        $user = $this->getMonitorLoginUser();
        $systemId = $user->subsystemId;
        $session = $this->getPost("session");//是否从session中获取
        $sql = "select s.system_logo_url,s.system_title from subsystem_info as s where s.id=$systemId";
        $systemData = $this->fetchOne($sql);
        if (!empty($session)) {
            if ($systemData){
                $user = array_merge($user, $systemData);
            }
            $this->returnJson($user);
        } else {
            $userId = $user->userId;
            $sql = "select user.*,b.user_role_id,b.system_name,b.system_id from user
left join
(select b.*,s.system_name from bind_user_system as b
	left join subsystem_info as s on s.id=b.system_id
) as b on b.user_id=user.id where user.id=$userId";
            $userInfo = $this->fetchOne($sql);
            $userInfo["roleName"] = $this->getRoleInfo()[$userInfo['user_role_id']];
            unset($userInfo['password']);
            unset($userInfo['password_salt']);
            unset($userInfo['salt']);
            if ($systemData){
                $userInfo = array_merge($userInfo, $systemData);
            }
            $this->returnJson($userInfo);
        }
    }

    //修改当前用户个人信息
    public function editProfileAction()
    {
        $user = $this->getMonitorLoginUser();
        $nickname = $this->getPost("nickname", $user->name, null);
        $sex = $this->getPost("sex", $user->sex, null);
        $email = $this->getPost("email", $user->email, null);
        $company = $this->getPost("company");
        $city = $this->getPost("city");
        $image_data = $this->getPost("image_data");
        $userId = $user->userId;

        $data=array(
            "nickname" => $nickname,
            "sex" => $sex,
            "email" => $email,
            "company" => $company,
            "city" => $city,
        );
        if($image_data){
            $uploadRet = $this->uploadIconCos($image_data, "user_" . $userId);
            if ($uploadRet['message'] != 0){
                return $this->returnError("上传失败");
            }else{
                $data['icon_url'] = $uploadRet;
            }
        }
        $result = $this->update("user",$data, "id=$userId");
        $user->name = $nickname;
        $user->email = $email;
        $user->iconUrl=$data['icon_url'];
        $this->session->set($this::SESSION_LOGIN_USER, $user);
        $this->returnSuccess("更新成功");
    }

//    public function editProfileAction()
//    {
//        // 数据有效性验证
//        $validation = new Phalcon\Validation();
//        $validation->add('sex', new RegexValidator(array('pattern' => '/^$|^[01]$|^null$/', 'message' => '性别只能是0、1、null')));
//        $this->checkRequest($validation, $this->request->getPost());
//
//        // 获得数据
//        $user = $this->getLoginUser();
//        $expire = $this->redisExpire['user'];
//        $nickname = $this->getPost("nickname");
//        $city = $this->getPost("city", $user['city'], null);
//        $sex = $this->getPost("sex", $user['sex'], null);
//        $icon_url = $this->getPost("icon_url", $user['icon_url'], null);
//        $company = $this->getPost("company", $user['company'], null);
//        $address = $this->getPost("address");
//        $comment = $this->getPost("comment");
//
//        if (empty($nickname)) {
//            $this->returnError("昵称不能为空。");
//        }
//
//        $sql = "UPDATE user
//                set nickname = '$nickname',
//                    city = '$city',
//                    sex = $sex,
//                    company = '$company',
//                    address = " . $this->getSqlTextField($address) . ",
//                    comment = " . $this->getSqlTextField($comment) . ",
//                    icon_url = '$icon_url',
//                    last_active_at = now()
//                where id = '" . $user['id'] . "'";
//        $this->dbExecute->execute($sql);
//
//        $sql = "select * from user where id = {$user['id']}";
//        $value = json_encode($this->dbQuery->fetchOne($sql, Phalcon\Db::FETCH_ASSOC), true);
//        $this->redis->setex("sql:$sql", $expire, $value);
//        $sql = "select * from user where phone = '{$user['phone']}'";
//        $this->redis->setex("sql:$sql", $expire, $value);
//        $sql = "select * from user where cloud_token = '{$user['cloud_token']}'";
//        $this->redis->setex("sql:$sql", $expire, $value);
//
//        $this->returnInfo("修改成功");
//    }

    // 发送手机验证码
    public function sendValidateAction()
    {
        // 数据有效性验证
        $validation = new Phalcon\Validation();
        $validation->add('phone', new RegexValidator(array('pattern' => '/^[0-9]{11}$/', 'message' => '手机号码格式不正确')));
        $this->checkRequest($validation, $this->request->getPost());

        $expire = 600;   //超时时间10分钟

        // 获得request
        $phone = $this->getPost("phone");

        // 检测用户是否存在
        $sql = "SELECT * FROM user where phone = '$phone'";
        $record = $this->fetchOne($sql);
        if ($record > 0) {
            $this->returnError('此用户已存在!');
        }

        if ($this->redis->exists("validate-$phone")) {
            // 如果redis中存在验证码
            $validate = $this->redis->get("validate-$phone");
            // 检测验证码发送周期
            if ($this->redis->ttl("validate-$phone") > $expire - 10) {
                $this->returnInfo('至少需要15秒才能重新发送验证码。');
            } else {
                $this->redis->setex("validate-$phone", $expire, $validate);
            }
        } else {
            // 如果redis中不存在，那么创建验证码和时间戳
            $validate = mt_rand(1000, 9999);
            $this->redis->setex("validate-$phone", $expire, $validate);
        }

        // 发送短信
        $result = $this->sendValidateSmsByInvoice($phone, $validate);

        if ($result['code'] != '0') {
            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($result) . " \r\n", FILE_APPEND);
            echo "发送失败";
        }

        $this->returnInfo("发送成功");
    }

    // 发送手机验证码
    public function validateSendSmsAction()
    {
//         include(dirname(__FILE__).'./../plugins/yunpian/YunpianConf.php');
        // 数据有效性验证
        $validation = new Phalcon\Validation();
        $validation->add('phone', new RegexValidator(array('pattern' => '/^[0-9]{11}$/', 'message' => '手机号码格式不正确')));
        $this->checkRequest($validation, $this->request->getPost());

        $expire = 600;
        // 获得request
        $phone = $this->getPost("phone");

        // 检测用户是否存在
        $sql = "SELECT * FROM user where phone = '$phone'";
        $record = $this->fetchOne($sql);
        if (!$record) {
            $this->returnError('用户不存在!');
        }

        if ($this->redis->exists("validate-$phone")) {
            // 如果redis中存在验证码
            $validate = $this->redis->get("validate-$phone");
            // 检测验证码发送周期
            if ($this->redis->ttl("validate-$phone") > $expire - 29) {
                $this->returnInfo('至少需要30秒才能重新发送验证码。');
            } else {
                $this->redis->setex("validate-$phone", $expire, $validate);
            }
        } else {
            // 如果redis中不存在，那么创建验证码和时间戳
            $validate = mt_rand(1000, 9999);
            $this->redis->setex("validate-$phone", $expire, $validate);
        }

        // 发送短信
        $result = $this->sendValidateSmsByInvoice($phone, $validate);

        if ($result['code'] != '0') {
            file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($result) . " \r\n", FILE_APPEND);
            echo "发送失败";
        }
        echo "发送成功";

//         $this->sendValidateSms($phone, $validate);
    }

    public function changePasswordAction()
    {

    }

    // 修改密码
    public function changePasswordDoAction()
    {
        $validation = new Phalcon\Validation();
        $validation->add('old_password', new StringLength(array('max' => 32, 'min' => 6, 'messageMaximum' => '密码为6到32位字符', 'messageMinimum' => '密码为6到32位字符')));
        $validation->add('password', new StringLength(array('max' => 32, 'min' => 6, 'messageMaximum' => '密码为6到32位字符', 'messageMinimum' => '密码为6到32位字符')));
        $validation->add('check_password', new StringLength(array('max' => 32, 'min' => 6, 'messageMaximum' => '密码为6到32位字符', 'messageMinimum' => '密码为6到32位字符')));
        $this->checkRequest($validation, $this->request->getPost());

        $expire = $this->redisExpire['user'];

        $password = $this->getPost('password');
        $checkPassword = $this->getPost('check_password');
        if ($password != $checkPassword) {
            $this->returnError("两次输入的密码不相同。");
        }
        $oldPassword = $this->getPost('old_password');
        $phone = $this->getLoginUser()['phone'];

        $userId = $this->getLoginUser()["id"];

        $sql = "select * from user where id = $userId";
        $record = $this->fetchOne($sql, $expire);
        if ($record['password_salt'] != bin2hex(hash('sha512', $oldPassword . '{' . $record['salt'] . '}', true))) {
            $this->returnError("原密码不正确。");
        }

        // 修改密码
        $sql = "update user set password='$password', password_salt = '" . bin2hex(hash('sha512', $password . '{' . $record['salt'] . '}', true)) . "' where phone = '$phone'";
        $this->dbExecute->execute($sql);

        $sql = "select * from user where id = {$record['id']}";
        $record['password'] = $password;
        $record['password_salt'] = bin2hex(hash('sha512', $password . '{' . $record['salt'] . '}', true));
        $value = json_encode($record, true);
        $this->redis->setex("sql:$sql", $expire, $value);
        $sql = "select * from user where phone = '$phone'";
        $this->redis->setex("sql:$sql", $expire, $value);
        $sql = "select * from user where cloud_token = '{$record['cloud_token']}'";
        $this->redis->setex("sql:$sql", $expire, $value);

        $this->returnInfo("修改密码成功");
    }

    public function resetPasswordAction()
    {

    }

    // 忘记密码重置密码
    public function resetPasswordDoAction()
    {
        $validation = new Phalcon\Validation();
        $validation->add('phone', new RegexValidator(array('pattern' => '/^[0-9]{11}$/', 'message' => '电话号码格式不正确')));
        $validation->add('validate', new Between(array('minimum' => 1000, 'maximum' => 9999, 'message' => '验证码格式不正确')));
        $validation->add('password', new StringLength(array('max' => 32, 'min' => 6, 'messageMaximum' => '密码为6到32位字符', 'messageMinimum' => '密码为6到32位字符')));
        $this->checkRequest($validation, $this->request->getPost());

        $phone = $this->getPost('phone');
        $validate = $this->getPost('validate');
        $password = $this->getPost('password');
        $repeatPassword = $this->getPost("repeat_password");

        $expire = $this->redisExpire['user'];

        if ($password != $repeatPassword) {
            $this->returnError("两次输入的密码不相同。");
        }

        // 校验是否存在该用户
        $sql = "select * from user where phone = '$phone'";
        //$this->returnDebug($sql);
        $record = $this->fetchOne($sql, $expire);
        if (empty($record)) {
            $this->returnError('用户不存在');
        }

        if ($validate == $this->redis->get("validate-$phone")) {
            // 密码正确，修改密码
            $sql = "update user set password='$password', password_salt = '" . bin2hex(hash('sha512', $password . '{' . $record['salt'] . '}', true)) . "' where phone = '$phone'";
            $this->dbExecute->execute($sql);

            $sql = "select * from user where id = {$record["id"]}";
            $record['password'] = $password;
            $record['password_salt'] = bin2hex(hash('sha512', $password . '{' . $record['salt'] . '}', true));
            $value = json_encode($record, true);
            $this->redis->setex("sql:$sql", $expire, $value);
            $sql = "select * from user where phone = '$phone'";
            $this->redis->setex("sql:$sql", $expire, $value);
            $sql = "select * from user where cloud_token = '{$token}'";
            $this->redis->setex("sql:$sql", $expire, $value);

            echo '密码重置成功';
//             $this->returnResponse(0, '密码重置成功', $record);
            //$this->returnJson($record);
            //$this->returnInfo("修改密码成功");
        } else {
            $this->returnWarning("验证码错误");
        }
    }

    public function changePhoneAction()
    {

    }

    // 修改绑定的电话号码
    public function changePhoneDoAction()
    {
        $validation = new Phalcon\Validation();
        $validation->add('phone', new RegexValidator(array('pattern' => '/^[0-9]{11}$/', 'message' => '电话号码格式不正确')));
        $validation->add('validate', new Between(array('minimum' => 1000, 'maximum' => 9999, 'message' => '验证码格式不正确')));
        $this->checkRequest($validation, $this->request->getPost());

        $phone = $this->request->getPost('phone');
        $validate = $this->request->getPost('validate');
        $password = $this->request->getPost('password');

        $expire = $this->redisExpire['user'];

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "login phone:$phone, password:$password, validate:$validate\r\n", FILE_APPEND);

        // 检查要变更的号码是否已经存在
        $sql = "select * from user where phone = $phone";
        $record = $this->fetchOne($sql);

        if (!empty($record)) {
            $this->returnError("号码已经在系统中存在了。");
        }

        $user = $this->getLoginUser();
        $userId = $user["id"];
        $oldPhone = $user["phone"];
        if ($validate != $this->redis->get("validate-$phone")) {
            $this->returnError("验证码不正确。");
        }

        if (!empty($password)) {
            $sql = "select * from user where id = $userId";
            $record = $this->fetchOne($sql, $expire);
            if ($record['password_salt'] != bin2hex(hash('sha512', $password . '{' . $record['salt'] . '}', true))) {
                $this->returnError("密码错误。");
            }
        }

        $sql = "update user set phone = '$phone' where id = $userId";
        $this->execute($sql);

        $sql = "select * from user where id = {$record["id"]}";
        $record['phone'] = $phone;
        $value = json_encode($record, true);
        $this->redis->setex("sql:$sql", $expire, $value);
        $sql = "select * from user where phone = '$phone'";
        $this->redis->setex("sql:$sql", $expire, $value);
        $sql = "select * from user where cloud_token = '{$token}'";
        $this->redis->setex("sql:$sql", $expire, $value);

        echo "修改成功！";
//         $this->returnJson(array(
//                 "old_phone" => $oldPhone,
//                 "new_phone" => $phone,
//         ));
        //$this->returnSuccess("修改成功！");
    }

    public function cityAction()
    {
        $id = $this->getQuery("id");
        if ($id == 0) {
            $sql = "select * from city where parent_id is not null";
            $records = $this->fetchAll($sql);
            $this->returnJson($records);
        } else if (empty($id)) {
            $sql = "select * from city where parent_id is null";
            $records = $this->fetchAll($sql);
            $this->returnJson($records);
        } else {
            $sql = "select * from city where parent_id = $id";
            $records = $this->fetchAll($sql);
            $this->returnJson($records);
        }
    }


    public function filedItemChanged($table, $name, $value)
    {

        switch ($name) {
            case "sex": {

                if ($value == null) {
                    return "未知";
                } else {
                    if ($value == "1") {
                        return "女";
                    } else {
                        return "男";
                    }
                }

            };
                break;
            case "permission_local_gps":
            case "permission_p40":
            case "video_route":
            case "online": {
                return $value == "1" ? "可用" : "不可用";
            };
                break;
            case "city":
            case "company":
            case "nickname": {
                if ($value == null) {
                    return "";
                }
            };
                break;

            case "login_type": {
                if ($value == "1") {
                    return "云监控平台";
                }
                if ($value == "0") {
                    return "无人机管家";
                }
            };
                break;
            case "type": {
                if ($value == "1") {
                    $value = "添加用户";
                }
            };
                break;
            case "status": {
                switch ($value) {
                    case "0": {
                        $value = "等待回复";
                    };
                        break;
                    case "1": {
                        $value = "未知";
                    };
                        break;
                    case "2": {
                        $value = "已通过";
                    };
                        break;
                    case "3": {
                        $value = "已拒绝";
                    };
                        break;
                }
            };
                break;
            case "system_name":
            case "real_name":
            case "contact_info":
            case "dept_name":
            case "receive_at": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "user_role_id": {
                if ($value == USER_ROLE_SUBSYSTEM_ADMIN) {
                    return "管理员";
                }
                if ($value == USER_ROLE_NORMAL) {
                    return "云用户";
                }
            };
                break;
        }
        return $value;
    }


//    public function testAction(){
//        //$this->returnSuccess(json_encode($this->defaultAuthMenu["admin"]));
//        //echo json_encode($this->defaultAuthMenu["admin"]);
//    }


}